<template>
    <div class="app-container">
        <el-card>
            <!-- 筛选条件行 -->
            <el-row :gutter="20" class="filter-row">
                <el-col :span="4">
                    <el-select v-model="queryParams.timeDimension" placeholder="时间维度" clearable
                        @change="handleTimeDimensionChange">
                        <el-option label="天" :value="1" />
                        <el-option label="月" :value="2" />
                        <el-option label="年" :value="3" />
                    </el-select>
                </el-col>
                <el-col :span="4">
                    <el-date-picker v-model="queryParams.time" :type="getDatePickerType()" placeholder="选择时间"
                        :format="getDateFormat()" value-format="YYYY-MM-DD" @change="handleFilterChange" />
                </el-col>

                <el-col :span="4">
                    <el-select v-model="queryParams.plantId" placeholder="全部水厂" clearable @change="handlePlantChange">
                        <el-option v-for="item in plantOptions" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-col>
                <el-col :span="4">
                    <el-select v-model="queryParams.siteIds" placeholder="全部站点" clearable multiple
                        @change="handleFilterChange">
                        <el-option v-for="item in siteOptions" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-col>
                <el-col :span="4">
                    <el-select v-model="queryParams.pumpGroupIds" placeholder="全部泵组" clearable multiple
                        @change="handleFilterChange">
                        <el-option v-for="item in pumpGroupOptions" :key="item.id" :label="item.pumpGroupName"
                            :value="item.id" />
                    </el-select>
                </el-col>
                <el-col :span="4">
                    <el-button type="success" icon="Download" @click="handleExport">导出数据</el-button>
                </el-col>
            </el-row>
        </el-card>

        <el-row :gutter="20">
            <!-- 顶部指标卡 -->
            <el-col :span="8">
                <el-card>
                    <div class="metric-card">
                        <h3>总用电量</h3>
                        <div class="value">{{ overviewData.totalKwh?.toLocaleString() || '--' }} kWh</div>
                        <div class="trend">
                            <span>千吨次电耗: {{ overviewData.kwhPerKt?.toFixed(1) || '--' }} kWh/kt</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card>
                    <div class="metric-card">
                        <h3>总电费</h3>
                        <div class="value">¥ {{ overviewData.totalCost?.toLocaleString() || '--' }}</div>
                        <div class="trend">
                            <span>单位电费: {{ getUnitCost() }} 元/kWh</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card>
                    <div class="metric-card">
                        <h3>运行效率</h3>
                        <div class="value">{{ getEfficiencyRate() }}%</div>
                        <div class="trend">
                            <span>运行泵组: {{ pumpGroupData.length }} 组</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 趋势图表区 -->
        <el-row :gutter="20" class="chart-row">
            <el-col :span="12">
                <el-card>
                    <Echarts :option="electricityChartOptions" height="400px" />
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card>
                    <Echarts :option="costChartOptions" height="400px" />
                </el-card>
            </el-col>
        </el-row>

        <!-- 泵组状态表格 -->
        <el-row>
            <el-col :span="24">
                <el-card>
                    <div class="table-header">
                        <h3>泵组运行状态</h3>
                        <el-button type="primary" size="small" @click="refreshPumpData">刷新数据</el-button>
                    </div>
                    <el-table :data="pumpGroupData" style="width: 100%">
                        <el-table-column prop="pumpGroupName" label="泵组名称" align="center" />
                        <el-table-column label="运行时长(h)" align="center">
                            <template #default="{ row }">
                                {{ row.runtimeHours || 0 }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="starts" label="启停次数" align="center" />
                        <el-table-column label="运行效率" align="center">
                            <template #default="{ row }">
                                <el-tag :type="getEfficiencyTagType(row.efficiency)">
                                    {{ row.efficiency ? (row.efficiency * 100).toFixed(1) + '%' : '--' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" align="center">
                            <template #default="{ row }">
                                <el-tag :type="row.status === '正常' ? 'success' : 'danger'">
                                    {{ row.status || '--' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="120">
                            <template #default="{ row }">
                                <el-button type="text" @click="viewPumpDetail(row)">详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-col>
        </el-row>

        <!-- 对比图表区 -->
        <el-row :gutter="20" class="chart-row">
            <el-col :span="12">
                <el-card>
                    <Echarts :option="pressureChartOptions" height="400px" />
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card>
                    <Echarts :option="flowChartOptions" height="400px" />
                </el-card>
            </el-col>
        </el-row>

        <!-- 优化建议区 -->
        <el-row :gutter="20">
            <el-col :span="24">
                <el-card>
                    <h3>能耗优化建议</h3>
                    <div class="optimization-content">
                        <div v-if="optimizationAdvices.length === 0" class="no-data">
                            <el-empty description="暂无优化建议" :image-size="80" />
                        </div>
                        <div v-else class="advice-list">
                            <div v-for="(advice, index) in optimizationAdvices" :key="index" class="advice-item">
                                <div class="advice-header">
                                    <el-tag :type="getAdviceLevel(advice.level)">{{ advice.level }}</el-tag>
                                    <span class="advice-title">{{ advice.title }}</span>
                                </div>
                                <div class="advice-content">{{ advice.content }}</div>
                                <div class="advice-footer">
                                    <span class="potential">预计节能: {{ advice.potential }}%</span>
                                    <span class="priority">优先级: {{ advice.priority }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import Echarts from '@/components/ECharts'
import dayjs from 'dayjs'

import {
    getFactoryList,
    getSiteList,
    getPumpGroupList,
    getEnergyOverview,
    getKwhTrend,
    getCostTrend,
    getPumpGroupStat,
    getPowerPressureCompare,
    getPowerFlowCompare
} from '@/api/dispatch/analyze/energy_consumption_analysis'

// 查询参数
const queryParams = reactive({
    timeDimension: 1,
    time: dayjs().format('YYYY-MM-DD'),
    plantId: '',
    siteIds: [],
    pumpGroupIds: [],
    tariffId: ''
})

// 下拉选项数据
const plantOptions = ref([])
const siteOptions = ref([])
const pumpGroupOptions = ref([])

// 数据状态
const overviewData = reactive({
    totalKwh: 0,
    totalCost: 0,
    kwhPerKt: 0
})

const kwhTrendData = ref({})
const costTrendData = ref({})
const pumpGroupData = ref([])
const pressureCompareData = ref([])
const flowCompareData = ref([])

// 加载状态
const tableLoading = ref(false)
const chartLoading = ref(false)

// 优化建议数据
const optimizationAdvices = ref([])

// 获取日期选择器类型
const getDatePickerType = () => {
    switch (queryParams.timeDimension) {
        case 1: return 'date'
        case 2: return 'month'
        case 3: return 'year'
        default: return 'date'
    }
}

// 获取日期格式
const getDateFormat = () => {
    switch (queryParams.timeDimension) {
        case 1: return 'YYYY年MM月DD日'
        case 2: return 'YYYY年MM月'
        case 3: return 'YYYY年'
        default: return 'YYYY年MM月DD日'
    }
}

// 时间维度变化处理
const handleTimeDimensionChange = (value) => {
    queryParams.timeDimension = value
    // 根据时间维度设置默认时间
    switch (value) {
        case 1:
            queryParams.time = dayjs().format('YYYY-MM-DD')
            break
        case 2:
            queryParams.time = dayjs().format('YYYY-MM')
            break
        case 3:
            queryParams.time = dayjs().format('YYYY')
            break
    }
    handleFilterChange()
}

// 水厂变化处理
const handlePlantChange = async (plantId) => {
    queryParams.plantId = plantId
    queryParams.siteIds = []
    queryParams.pumpGroupIds = []

    if (plantId) {
        await fetchSiteList(plantId)
    } else {
        siteOptions.value = []
        pumpGroupOptions.value = []
    }
    handleFilterChange()
}

// 处理筛选变化
const handleFilterChange = () => {
    fetchAllData()
    fetchPumpGroupList(queryParams.siteIds)
}

// 获取站点列表
const fetchSiteList = async (plantId) => {
    try {
        const res = await getSiteList({ factoryId: plantId })
        siteOptions.value = res.data || []
    } catch (error) {
        console.error('获取站点列表失败:', error)
        ElMessage.error('获取站点列表失败')
    }
}

// 获取泵组列表
const fetchPumpGroupList = async (siteIds) => {
    try {
        const res = await getPumpGroupList(siteIds);

        pumpGroupOptions.value = res.data || []
    } catch (error) {
        console.error('获取泵组列表失败:', error)
        ElMessage.error('获取泵组列表失败')
    }
}

// 获取所有数据
const fetchAllData = async () => {
    tableLoading.value = true
    chartLoading.value = true

    // 并行获取所有数据
    const [
        overviewRes,
        kwhTrendRes,
        costTrendRes,
        pumpStatRes,
        pressureRes,
        flowRes
    ] = await Promise.all([
        getEnergyOverview(queryParams),
        getKwhTrend(queryParams),
        getCostTrend(queryParams),
        getPumpGroupStat(queryParams),
        getPowerPressureCompare({
            siteId: queryParams.siteIds?.[0] || '',
            day: queryParams.time
        }),
        getPowerFlowCompare({
            siteId: queryParams.siteIds?.[0] || '',
            day: queryParams.time
        })
    ])

    // 处理返回数据
    Object.assign(overviewData, overviewRes.data || {})
    kwhTrendData.value = kwhTrendRes.data || {}
    costTrendData.value = costTrendRes.data || {}
    pumpGroupData.value = pumpStatRes.data || []
    pressureCompareData.value = pressureRes.data || []
    console.log(pressureCompareData.value);

    flowCompareData.value = flowRes.data || []

    // 生成优化建议
    generateOptimizationAdvices()

}

// 生成优化建议
const generateOptimizationAdvices = () => {
    const advices = []

    // 基于数据分析生成建议
    if (overviewData.kwhPerKt > 400) {
        advices.push({
            level: '高',
            title: '千吨次电耗偏高',
            content: '当前千吨次电耗较高，建议检查泵组运行效率，优化运行策略',
            potential: '15-20',
            priority: '高'
        })
    }

    if (pumpGroupData.value.some(pump => pump.efficiency < 0.8)) {
        advices.push({
            level: '中',
            title: '部分泵组效率偏低',
            content: '检测到部分泵组运行效率低于80%，建议进行设备维护或更换',
            potential: '8-12',
            priority: '中'
        })
    }

    if (overviewData.totalKwh > 500000) {
        advices.push({
            level: '中',
            title: '总用电量较大',
            content: '总用电量较大，建议实施峰谷电价策略，优化用电时段',
            potential: '10-15',
            priority: '中'
        })
    }

    optimizationAdvices.value = advices
}

// 计算单位电费
const getUnitCost = () => {
    if (overviewData.totalKwh && overviewData.totalCost) {
        return (overviewData.totalCost / overviewData.totalKwh).toFixed(2)
    }
    return '--'
}

// 计算运行效率
const getEfficiencyRate = () => {
    if (pumpGroupData.value.length === 0) return '--'
    const avgEfficiency = pumpGroupData.value.reduce((sum, pump) => {
        return sum + (pump.efficiency || 0)
    }, 0) / pumpGroupData.value.length
    return (avgEfficiency * 100).toFixed(1)
}

// 效率标签类型
const getEfficiencyTagType = (efficiency) => {
    if (!efficiency) return 'info'
    if (efficiency >= 0.9) return 'success'
    if (efficiency >= 0.8) return 'warning'
    return 'danger'
}

// 建议级别标签类型
const getAdviceLevel = (level) => {
    switch (level) {
        case '高': return 'danger'
        case '中': return 'warning'
        case '低': return 'info'
        default: return 'info'
    }
}

// 图表配置 - 电量趋势
const electricityChartOptions = computed(() => {
    const seriesData = kwhTrendData.value.points || []
    const xAxisData = seriesData.map(item => {
        if (queryParams.timeDimension === 1) {
            return dayjs(item.date).format('HH:mm')
        } else if (queryParams.timeDimension === 2) {
            return dayjs(item.date).format('MM-DD')
        } else {
            return dayjs(item.date).format('YYYY-MM')
        }
    })
    const yAxisData = seriesData.map(item => item.value)

    return {
        title: {
            text: '电量趋势',
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                return `${params[0].axisValue}<br/>电量: ${params[0].value} kWh`
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            name: '电量 (kWh)'
        },
        series: [{
            name: '电量',
            type: 'line',
            data: yAxisData,
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
                color: '#36a3f7'
            },
            lineStyle: {
                width: 2
            },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                        offset: 0,
                        color: 'rgba(54, 163, 247, 0.3)'
                    }, {
                        offset: 1,
                        color: 'rgba(54, 163, 247, 0.1)'
                    }]
                }
            }
        }]
    }
})

// 图表配置 - 电费趋势
const costChartOptions = computed(() => {
    const seriesData = costTrendData.value.points || []
    const xAxisData = seriesData.map(item => {
        if (queryParams.timeDimension === 1) {
            return dayjs(item.date).format('HH:mm')
        } else if (queryParams.timeDimension === 2) {
            return dayjs(item.date).format('MM-DD')
        } else {
            return dayjs(item.date).format('YYYY-MM')
        }
    })
    const yAxisData = seriesData.map(item => item.value)

    return {
        title: {
            text: '电费趋势',
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                return `${params[0].axisValue}<br/>电费: ¥${params[0].value}`
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            name: '电费 (元)'
        },
        series: [{
            name: '电费',
            type: 'line',
            data: yAxisData,
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
                color: '#ff6384'
            },
            lineStyle: {
                width: 2
            },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                        offset: 0,
                        color: 'rgba(255, 99, 132, 0.3)'
                    }, {
                        offset: 1,
                        color: 'rgba(255, 99, 132, 0.1)'
                    }]
                }
            }
        }]
    }
})

// 图表配置 - 电耗 vs 压力对比
const pressureChartOptions = computed(() => {
    const seriesData = pressureCompareData.value
    if (!seriesData || seriesData.length === 0) {
        return getEmptyChartOption('电耗与出口压力对比')
    }

    return {
        title: {
            text: '电耗与出口压力对比',
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        legend: {
            data: seriesData.map(item => item.label),
            bottom: 0
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: seriesData[0]?.points.map(item => item.date.split(' ')[1].slice(0,2)),
            axisLabel: {
            }
        },
        yAxis: [{
            type: 'value',
            name: '电耗 (kWh)',
            position: 'left'
        }, {
            type: 'value',
            name: '压力 (MPa)',
            position: 'right'
        }],
        series: seriesData.map((item,index) => ({
            name: item.label,
            type: 'line',
            data: item.points.map(chi => chi.value),
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
                width: 2
            }
        }))
    }
})

// 图表配置 - 电耗 vs 流量对比
const flowChartOptions = computed(() => {
    const seriesData = flowCompareData.value
    if (!seriesData || seriesData.length === 0) {
        return getEmptyChartOption('电耗与出口流量对比')
    }

    const xAxisData = seriesData[0]?.points?.map(item => dayjs(item.date).format('HH:mm')) || []
    const powerData = seriesData.find(s => s.label === '电耗')?.points?.map(item => item.value) || []
    const flowData = seriesData.find(s => s.label === '流量')?.points?.map(item => item.value) || []

    return {
        title: {
            text: '电耗与出口流量对比',
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        legend: {
            data: seriesData.map(item => item.label),
            bottom: 0
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: seriesData[0]?.points.map(item => item.date.split(' ')[1].slice(0,2)),
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: [{
            type: 'value',
            name: '电耗 (kWh)',
            position: 'left'
        }, {
            type: 'value',
            name: '流量 (m³/h)',
            position: 'right'
        }],
        series: seriesData.map((item,index) => ({
            name: item.label,
            type: 'line',
            data: item.points.map(chi => chi.value),
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
                width: 2
            }
        }))
    }
})

// 空图表配置
const getEmptyChartOption = (title) => {
    return {
        title: {
            text: title,
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            data: [],
            type: 'line'
        }]
    }
}

// 查看泵组详情
const viewPumpDetail = (row) => {
    ElMessage.info(`查看泵组详情: ${row.pumpGroupName}`)
    // 这里可以打开详情对话框或跳转到详情页面
}

// 刷新泵组数据
const refreshPumpData = () => {
    fetchAllData()
}

// 导出数据
const handleExport = () => {
    ElMessage.info('导出功能待实现')
}

// 初始化数据
const initData = async () => {
    try {
        // 获取水厂列表
        const factoryRes = await getFactoryList()
        plantOptions.value = factoryRes.data || []
        if (plantOptions.value.length > 0) {
            queryParams.plantId = plantOptions.value[0].dictValue
            await fetchSiteList(queryParams.plantId)
        }

        // 获取站点列表
        const siteRes = await getSiteList({ factoryId: queryParams.plantId })
        siteOptions.value = siteRes.data || []
        if (siteOptions.value.length > 0) {
            queryParams.siteIds = [siteOptions.value[0].dictValue]
        }

        // // 获取泵组列表
        const pumpGroupRes = await getPumpGroupList(queryParams.siteIds);
        pumpGroupOptions.value = pumpGroupRes.data || []
        console.log(pumpGroupOptions);


        fetchPumpGroupList(queryParams.siteIds);

        await fetchAllData()
    } catch (error) {
        console.error('初始化数据失败:', error)
        ElMessage.error('初始化数据失败')
    }
}

onMounted(() => {
    initData()
})
</script>

<style scoped lang="scss">
.app-container {
    padding: 20px;
}

.filter-row {
    margin-bottom: 0;
}

.metric-card {
    text-align: center;
    padding: 20px 0;
}

.metric-card h3 {
    margin: 0 0 10px 0;
    font-size: 16px;
    color: #666;
}

.metric-card .value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
    color: #1890ff;
}

.metric-card .trend {
    font-size: 14px;
    color: #999;
}

.chart-row {
    margin: 20px 0;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.table-header h3 {
    margin: 0;
}

.optimization-content {
    min-height: 200px;
}

.no-data {
    text-align: center;
    padding: 40px 0;
}

.advice-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.advice-item {
    padding: 16px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    background: #fafafa;
}

.advice-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.advice-title {
    margin-left: 8px;
    font-weight: bold;
    font-size: 14px;
}

.advice-content {
    margin-bottom: 8px;
    color: #666;
    line-height: 1.5;
}

.advice-footer {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #999;
}

.potential {
    color: #f56c6c;
    font-weight: bold;
}

.priority {
    color: #1890ff;
}

:deep(.el-card) {
    margin-bottom: 20px;
}

:deep(.el-table) {
    margin-top: 0;
}
</style>